#include <buola/gui.h>

#include <buola/algorithm/comparison.h>

#include <buola/app/cplugin.h>

#include <buola/gui/cpropertyfield.h>

#include <buola/widgets/cwidgetfactory.h>

namespace buola { namespace gui {

std::vector<std::unique_ptr<CWidgetFactory>> CWidgetFactory::mFactories;
bool CWidgetFactory::mLoaded=false;

CWidgetFactory::CWidgetFactory()
{
    mProperties.emplace_back(new CPropertyField(L"string",L"caption",L"caption"));
    mIcon=nullptr;
}

CWidgetFactory::~CWidgetFactory()
{
}

PIcon CWidgetFactory::GetIcon()
{
    if(!mIcon)
        mIcon=CIcon::Get(mIconName);
    if(!mIcon)
        msg_warn() << "Can't load icon " << mIconName << "\n";
    return mIcon;
}

CWidgetFactory *CWidgetFactory::GetFactory(const std::wstring &pName)
{
    if(!mLoaded) LoadAll();

    for(int i=0;i<mFactories.size();i++)
    {
        if(iequals(mFactories[i]->mName,pName))
            return mFactories[i].get();
    }

    return nullptr;
}

void CWidgetFactory::RemoveProperty(const std::wstring &pWhich)
{
    for(int i=0;i<mProperties.size();i++)
    {
        if(equals(mProperties[i]->mName,pWhich))
        {
            mProperties.erase(mProperties.begin()+i);
            return;
        }
    }

    throw XNotFound("Can't delete property because it doesn't exist");
}

void CWidgetFactory::LoadAll()
{
    CPlugin::LoadAll("widgets");

    mLoaded=true;
}

void CWidgetFactory::Add(CWidgetFactory *pFactory)
{
    msg_debug<15>() << "Added plugin for " << pFactory->mName << " widget\n";

    mFactories.emplace_back(pFactory);
}

/*namespace gui*/ } /*namespace buola*/ }
